package ipmss.ui.validators;

import ipmss.ui.common.Messages;

import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import javax.faces.application.FacesMessage;
import javax.faces.application.FacesMessage.Severity;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.RegexValidator;
import javax.faces.validator.ValidatorException;

// TODO: Auto-generated Javadoc
/**
 * The Class MyRegexValidator.
 *
 * @author Michał Czarnik
 */
public class MyRegexValidator extends RegexValidator
{
    /**
     * 
     * </p>Validate a String against a regular expression pattern. The full
     * regex pattern must be matched in order to pass the validation.</p>
     * 
     * @param context
     *            {@inheritDoc}
     * @param component
     *            {@inheritDoc}
     * @param value
     *            {@inheritDoc}
     * 
     * @throws NullPointerException
     *             {@inheritDoc}
     * @throws ValidatorException
     *             {@inheritDoc}
     */
    @Override
    public void validate(FacesContext context, UIComponent component, Object value)
    {

	setPattern((String) component.getAttributes().get("pattern"));
	
	if (context == null)
	{
	    throw new NullPointerException();
	}
	if (component == null)
	{
	    throw new NullPointerException();
	}

	if (value == null)
	{
	    return;
	}

	FacesMessage fmsg;

	Locale locale = context.getViewRoot().getLocale();

	if (getPattern() == null || getPattern().length() == 0)
	{
	    fmsg = Messages.getMessage(FacesMessage.SEVERITY_ERROR,"no pattern", null);
	    throw new ValidatorException(fmsg);
	}

	try
	{
	    Pattern pattern = Pattern.compile(getPattern());
	    Matcher matcher = pattern.matcher((String) value);
	    if (!matcher.matches())
	    {
		Object[] params = {component.getAttributes().get("label"),getPattern()};
		fmsg = Messages.getMessage(FacesMessage.SEVERITY_ERROR,"common.inputInvalid", params);
		throw new ValidatorException(fmsg);
	    }
	} catch (PatternSyntaxException pse)
	{
	    fmsg = Messages.getMessage(FacesMessage.SEVERITY_ERROR,"syntax exception", null);
	    throw new ValidatorException(fmsg, pse);
	}
    }

}
